package com.ljsw.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.ljsw.adapter.ADDBiaoPaiInfoAdapter;
import com.ljsw.adapter.PKReconciDialogadapter;
import com.ljsw.adapter.PKReconcilAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.PKBiaoPaiDiaglog.PKBiaoPaiDialog;
import com.ljsw.dialog.SubmitDialog;
import com.ljsw.dialog.SuccessDialog;
import com.ljsw.dialog.WritePadDialog;
import com.ljsw.entity.DetailsEntity;
import com.ljsw.entity.PKReonciliationEntity;
import com.ljsw.entity.gpk.NotcompeteNumState;
import com.ljsw.entity.pkentity.Reconcil.PKReconcolEntity;
import com.ljsw.entity.pkentity.Reconcil.PKReconcolEntityCode;
import com.ljsw.server.UpServer;
import com.ljsw.util.BitmapUtil;
import com.ljsw.util.DialogListener;
import com.ljsw.util.DialogManager;
import com.ljsw.util.MD5;
import com.poka.embedextract.FileOperation;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Environment.getExternalStorageDirectory;
import static com.ljsw.application.App.app;
import static com.ljsw.application.App.user;

/****
 * 待对账标牌状态修改
 * 20201102
 * implements AdapterView.OnItemClickListener
 */
//public class PKReconciliationActivity extends FragmentActivity implements View.OnClickListener, PKReconcilAdapter.Callback {
public class PKReconciliationActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, Thread.UncaughtExceptionHandler {
    private static final String TAG = "PKReconciliationActivity";
    private TextView pkreconciliationuser, taskno, PKRCMonetcout, PKReconciliationzongjine, PKRCA_ATMMoney, PKRCA_Diaojao;//  操作人,任务编号,库存编号, 标牌扫描合计金额,  ATM  调缴
    private TextView pkreconcilitaother;//  其他
    private TextView pk_reconcitionchagestate;//  修改标牌状态
    private ListView listviewnpkConciliation;
    private PKReconcilAdapter PKReconcilAdapter;
    private List<PKReconcolEntity> PKReconcolEntitylist = new ArrayList<PKReconcolEntity>();
    private List<PKReconcolEntityCode> EntitycodeList = new ArrayList<PKReconcolEntityCode>();
    private TextView pkrecomtaskno;
    private File file;
    private TextView tv_sign1;// 签名提示
    private ImageView iv_sign1, iv_sign2;// 签名图片
    // ArrayList<Bitmap> photoPaths = new ArrayList<Bitmap>(); // 保存拍照相片的集合
    private String strPath; // 拍照后相片保存的绝对路径
    private List<String> pathlist = new ArrayList<String>();// 图片路径集合
    private List<String> namelist = new ArrayList<String>();// 图片名集合
    private ArrayList<String> photoPaths = new ArrayList<String>();// 图片名集合
    private Bundle bundle;
    private int imageNum = 0;// 上传图片的数量

    private LinearLayout zzxlist_layout,// 填充器（美化UI,周转箱）
            zzxlist_layout_view,// 填充器（周转箱列表）
            zzxlist_check,// 核对布局（重扫，确认）
            qianmingLayout;// 签名人员布局
    private String embed = "";// 水印内容
    FileOperation operation = new FileOperation();
    private String embedPath = "";
    private String leftName, rightName;// 左签名和右签名
    private PKBiaoPaiDialog pkBiaoPaiDialog;//  选择标牌
    private ADDBiaoPaiInfoAdapter addbiaopaiAdapter;

    private Button PKReconcilia_btn_true;//  确定提交代码
    private TextView btnchangesate;//  min
    private TextView PKRCMonetcoutinfo;//  明细查看

    private ImageView preconcliationblack;//  返回按钮
    private Handler handler;
    //--------------------------------------------------------
    private String atmCashReplenishment;//   atm  金额
    private String scanTotalAmount;//  扫描库存核心金额
    private String TaskNo;// 任务编号
    private String Userid;//    操作人编号
    private String transferFunds;// 调缴金额
    private String otherFunds;//  其他
    //    private String       scanTotalAmount  ;//  扫描后的金额
    private String coreInventoryAmount;//  核心库存金额

    //----集合
    private List<DetailsEntity> detailList001 = new ArrayList<DetailsEntity>();// 接受6.2返回集合代码
    private List<String> NotCompleLoadDataALLlist = new ArrayList<String>();//接口6.2 获取全部的数据
    private List<NotcompeteNumState> sacnlist = new ArrayList<NotcompeteNumState>(); //  获取扫描到的数据6.1
    private List<String> sacnlist1 = new ArrayList<String>(); //  获取扫描到的数据6.1
    private List<NotcompeteNumState> unscanlist = new ArrayList<NotcompeteNumState>();//  获取上面两个集合差值

    private List<NotcompeteNumState> showlist = new ArrayList<NotcompeteNumState>();//  显示列表

    private List<String> dialogshowlist = new ArrayList<String>();//  显示列表

    private String UserName;//  用户名称
    private DialogManager dmanager;// 弹出框管理类
    //    private PKReconciDialog pkreconciDialog;// 弹出框管理类
    private Context context;
    private ProgressDialog progressDialog;
    private Button hbt_ql_ruku_update;// 更新
    private SuccessDialog successDialog;
    private SubmitDialog subDialog;
    String result = "";// 提交后的返回结果
    private String strLibrary = "";//  库存编号
    private TextView PKreconciliationcheckNO;  //  库存编号view'
    private List<PKReonciliationEntity> PKReonciliationEntitylist = new ArrayList<PKReonciliationEntity>();//
    private com.ljsw.dialog.LoadIngDialog LoadIngDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pkreconciliation);
        Thread.setDefaultUncaughtExceptionHandler(PKReconciliationActivity.this);
        TaskNo = getIntent().getStringExtra("PKNO");//  上一个页面的任务号码
        strLibrary = getIntent().getStringExtra("inventoy");
        context = PKReconciliationActivity.this;
        InitView();

        dmanager = new DialogManager(PKReconciliationActivity.this);
//        LoadIngDialog = dmanager.getLoadIngDialog().builder();
        dmanager = new DialogManager(this);
        LoadIngDialog = dmanager.getLoadIngDialog().builder();
        LoadData();

//        LoadDataScan();
        loadDataImage();
        Userid = app.userZhanghao;
        UserName = app.user.getName();

        dmanager = new DialogManager(context);
//        pkreconciDialog = dmanager.getPkReconciDialog();
        this.progressDialog = new ProgressDialog(context);
        this.progressDialog.setCancelable(false);


        successDialog = dmanager.getSuccessDialog();
        subDialog = dmanager.getSubmitDialog();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0://   传时间获取数据成功
                        Log.d("login用户role------------", user.getUserId());
                        PKReconcilAdapter.notifyDataSetChanged();
                        break;
                    case 1://登录超时

                        NotCompleLoadDataALL();

                        break;
                    case 22:
                        showlist.clear();
//                        for (int i = 0; i < NotCompleLoadDataALLlist.size(); i++) {

                        setData();
                        if (PKReconcilAdapter == null) {
                            PKReconcilAdapter = new PKReconcilAdapter(showlist, PKReconciliationActivity.this);
                            listviewnpkConciliation.setAdapter(PKReconcilAdapter);
                        } else {
                            PKReconcilAdapter.notifyDataSetChanged();
                        }
                        PKRCMonetcout.setText(coreInventoryAmount);//   设置库存金额
                        PKReconciliationzongjine.setText(scanTotalAmount);//  标牌扫描金额
                        PKRCA_ATMMoney.setText(atmCashReplenishment);// ATM金额
                        PKRCA_Diaojao.setText(transferFunds); // 调缴
                        pkreconcilitaother.setText(otherFunds); // 其他
                        PKreconciliationcheckNO.setText(strLibrary);//  库存编号

                        break;
                    case 2://用户不存在
//                        Toast.makeText(PKReconciliationActivity.this, " 图片提交", Toast.LENGTH_SHORT).show();
                        break;
                    case 3://异常加载，无法访问服务器
                        Toast.makeText(PKReconciliationActivity.this, "" + "加载异常", Toast.LENGTH_SHORT).show();
                        break;

                    case 5:
                        Toast.makeText(PKReconciliationActivity.this, "更新失败请重试", Toast.LENGTH_SHORT).show();
                        break;

                    case 6://用户不正确
                        Toast.makeText(PKReconciliationActivity.this, "更新成功请刷新", Toast.LENGTH_SHORT).show();

                        View successbottomViewregon = View.inflate(PKReconciliationActivity.this, R.layout.dialog_updata, null);//填充ListView布局
                        final AlertDialog sucparkIdsdialogregon = new AlertDialog.Builder(context)
                                .setTitle("标牌状态更新成功请刷新").setView(successbottomViewregon)//在这里把写好的这个listview的布局加载dialog中
                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        successDialog.dismiss();
                                        NotCompleLoadData();

                                    }
                                }).create();
                        sucparkIdsdialogregon.show();

//                        NotCompleLoadDataALL();

                        PKReconcilAdapter.notifyDataSetChanged();
                        break;
                    case 7://用户不正确
                        Toast.makeText(PKReconciliationActivity.this, "请检查用户名", Toast.LENGTH_SHORT).show();
                        break;
                    case 8://用户不正确
                        Toast.makeText(PKReconciliationActivity.this, "无返回结果", Toast.LENGTH_SHORT).show();
                        break;
                    case 9://用户不正确
                        break;

                    case 15:
                        /**
                         * 进度条显示
                         */
                        showJindu();
                        progressDialog.dismiss();
                        break;
                    case 16:
                        Toast.makeText(PKReconciliationActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                        break;

                    case 17:
                        progressDialog.dismiss();
                        // 调用提交任务接口
                        submit();
                        break;
                    case 18:

                        successDialog = dmanager.getSuccessDialog().builder();
                        subDialog.dismiss();
//                        successDialog.show();
//                        successDialog.success();
                        View successbottomView = View.inflate(PKReconciliationActivity.this, R.layout.dialog_updata_succcess, null);//填充ListView布局
                        TextView dialog_success01 = (TextView) successbottomView.findViewById(R.id.dialog_success01);
                        dialog_success01.setText("提交成功");
                        final AlertDialog sucparkIdsdialog = new AlertDialog.Builder(context)
                                .setTitle("提交成功").setView(successbottomView)//在这里把写好的这个listview的布局加载dialog中
                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        successDialog.dismiss();
                                        Intent intent = new Intent(PKReconciliationActivity.this, PKListInfoActivity.class);

                                        startActivity(intent);
                                        PKReconciliationActivity.this.finish();

                                    }
                                }).create();
                        sucparkIdsdialog.show();

                        break;
                    case 19:

//                        Toast.makeText(PKReconciliationActivity.this, "提交失败" + result, Toast.LENGTH_SHORT).show();


                        View bottomView = View.inflate(PKReconciliationActivity.this, R.layout.dialog_updata, null);//填充ListView布局
//                        TextView dialog_success02 = (TextView) bottomView.findViewById(R.id.dialog_success01);
//                        dialog_success02.setText("提交失败");
                        final AlertDialog parkIdsdialog = new AlertDialog.Builder(context)
                                .setTitle("提交信息" + result).setView(bottomView)//在这里把写好的这个listview的布局加载dialog中
                                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("重试", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        UploadnImage();
                                    }
                                }).create();
                        parkIdsdialog.show();


                        break;
                    case 20:
                        PKReconcilAdapter.notifyDataSetChanged();
                        break;
                    case 21:
                        Toast.makeText(PKReconciliationActivity.this, "程序解析失败", Toast.LENGTH_SHORT).show();
                        break;


                    case 30:
                        Toast.makeText(PKReconciliationActivity.this, "提交数据返回结果为空", Toast.LENGTH_SHORT).show();

                        break;
                    case 31:
                        Toast.makeText(PKReconciliationActivity.this, "提交数据返回结果不是数字", Toast.LENGTH_SHORT).show();
                        break;

                    case 33:
                        Toast.makeText(PKReconciliationActivity.this, "提交数据失败返回为空", Toast.LENGTH_SHORT).show();

                        break;

                    case 40:

                        Toast.makeText(PKReconciliationActivity.this, "只有扫描状态的标牌才能添加明细", 400).show();
                        break;
                    case 41:

                        Toast.makeText(PKReconciliationActivity.this, "正在数据处理请稍等", 400).show();
                        break;
                    case 50:
                        LoadIngDialog.dismiss();  //去点遮罩
                        break;

                    default:
                        Toast.makeText(PKReconciliationActivity.this, "请检查网络服务", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }


    //    if ("00".equals(result)) {
    private void setData() {
        showlist.clear();
        List<String> list1 = new ArrayList<String>();
        list1.clear();
        if (sacnlist.size() == 0) {
            for (int i = 0; i < NotCompleLoadDataALLlist.size(); i++) {
                NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                notcompeteNumState.setNotno(NotCompleLoadDataALLlist.get(i));
                notcompeteNumState.setState("0");
                showlist.add(notcompeteNumState);
            }
        } else {//  未扫描已经扫描同时存在
            for (int p = 0; p < NotCompleLoadDataALLlist.size(); p++) {
                for (int s = 0; s < sacnlist.size(); s++) {
                    if (NotCompleLoadDataALLlist.get(p).equals(sacnlist.get(s).getNotno())) {
                        NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                        notcompeteNumState.setNotno(sacnlist.get(s).getNotno());
                        notcompeteNumState.setState(sacnlist.get(s).getState());
                        showlist.add(notcompeteNumState);
                    } else {


//                        list1 = NotCompleLoadDataALLlist;
                        list1.add(NotCompleLoadDataALLlist.get(p));

                    }

                }
            }
            List<String> scanlist001 = new ArrayList<String>(); ///  全部数据-已扫描集合
            scanlist001 = NotCompleLoadDataALLlist;

            for (int i = 0; i < NotCompleLoadDataALLlist.size(); i++) {
                for (int j = 0; j < sacnlist1.size(); j++) {
                    String strlist1 = (NotCompleLoadDataALLlist.get(i));
                    String strscanlist1 = sacnlist1.get(j);
                    Log.e(TAG, strlist1 + "strlist1EEEEEEEEEEEEE");
                    Log.e(TAG, strscanlist1 + "strscanlist1EEEEEEEEEEEEE");
                    if (NotCompleLoadDataALLlist.contains(strscanlist1)) {
                        scanlist001.remove(strscanlist1);

                    }


                }

            }
            Log.e(TAG, list1.size() + "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
            System.out.print("----------------------" + list1.size());

            for (int i = 0; i < scanlist001.size(); i++) {
                NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                notcompeteNumState.setNotno(scanlist001.get(i));
                notcompeteNumState.setState("0");
                showlist.add(notcompeteNumState);

            }

        }


    }


    /***
     * //    接口名 ：inventoryReconciliation
     * //    参数名 ：   checkId	任务编号              必填
     * //    storekeeperName	库管员名字  必填
     * //    userId	用户id    必填
     */
    String arg3 = App.user.getName();//  操作人
    String arg4 = App.userZhanghao;//  操作人账号

    private void submit() {


        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    result = UpServer.inventoryReconciliation(TaskNo, arg4, arg3);
                    if ("00".equals(result)) {
                        handler.sendEmptyMessage(18);
                    } else {// 失败
                        handler.sendEmptyMessage(19);
                    }
                } catch (SocketException e) {// 超时
                    e.printStackTrace();
                    handler.sendEmptyMessage(16);
                } catch (Exception e) {// 失败
                    e.printStackTrace();
                    handler.sendEmptyMessage(16);
                }
            }

        }.start();
    }

//    /**
//     * 获取扫描数据
//     */
//    private void LoadDataScan() {
//    }
//
//    public static String getJson(Context context, String fileName) {
//        StringBuilder stringBuilder = new StringBuilder();
//        //获得assets资源管理器
//        AssetManager assetManager = context.getAssets();
//        //使用IO流读取json文件内容
//        try {
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
//                    assetManager.open(fileName), "utf-8"));
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                stringBuilder.append(line);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return stringBuilder.toString();
//    }

    /**
     * 获取网络数据
     */
    private String Taskno;

    private void LoadData() {
//        String json = getJson(this, "pkdiaduizhangbiaopaizhuangtaixiugai.json");
//        Log.e(TAG, "json=============================================" + json);
////        Gson gson = new Gson();
////        PKReconcolEntityCode[] lmcode = gson.fromJson(json,
////                PKReconcolEntityCode[].class);
////
////        for (int i = 0; i < lmcode.length; i++) {
////            EntitycodeList = Arrays.asList(lmcode);
////        }
//        PKReconcolEntityCode categoryBean = JSONObject.parseObject(json, PKReconcolEntityCode.class);
//
//        Log.e(TAG, "getCode=============================================" + categoryBean.getCode());
//        for (int i = 0; i < categoryBean.getData().size(); i++) {
//            PKReconcolEntitylist.add(categoryBean.getData().get(i));
//        }
//        for (int i = 0; i < EntitycodeList.size(); i++) {
//            PKReconcolEntitylist = EntitycodeList.get(i).getData();
//
//        }
    }

    /***
     * 获取数据
     * {"repertory":null,"detailList":[{"SCUTCHEONSNUM":"BP001","SCUTCHEONNAME":"BP001","details":[],
     * "SCUTCHEONSTATE":0,"ADDTIME":"2020-11-04","SCUTCHEONID":187,"ADDNAME":"系统管理"}]}
     */
    String NotCompleLoadDataALL = "";

    private void NotCompleLoadDataALL() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    PKReonciliationEntitylist.clear();
                    detailList001.clear();
                    NotCompleLoadDataALL = UpServer.repertoryInfo(strLibrary, Userid);
                    Log.e(TAG, "=========NotCompleLoadDataALL==" + NotCompleLoadDataALL);
                    NotCompleLoadDataALLlist.clear();
                    JSONObject obj = JSONObject.parseObject(NotCompleLoadDataALL);
                    String repertory = obj.getString("repertory");
                    JSONObject jsondata = JSONObject.parseObject(repertory);
                    if (null == jsondata) {
                    } else {
//                        scanTotalAmount = jsondata.getString("scanTotalAmount");//    // '扫描合计金额'
//                    盘查库总金额
                    }
                    JSONArray arr = obj.getJSONArray("detailList");
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject jsonArray = arr.getJSONObject(i);
                        String checkId = jsonArray.getString("SCUTCHEONSNUM");// 标牌编号
                        String cheid01 = checkId.replace('\"', '\'');
                        String SCUTCHEONNAME = jsonArray.getString("SCUTCHEONNAME");// 标牌名称
                        JSONArray detailsarr1 = jsonArray.getJSONArray("details");
                        DetailsEntity De = new DetailsEntity();
                        De.setSCUTCHEONNAME(SCUTCHEONNAME);
                        De.setSCUTCHEONSNUM(checkId);
                        List<PKReonciliationEntity> PKReonciliationEntitylist = new ArrayList<PKReonciliationEntity>();//
                        if (detailsarr1 != null) {

                            for (int x = 0; x < detailsarr1.size(); x++) {
                                JSONObject jsonArray1 = detailsarr1.getJSONObject(x);
                                String MONEYDETAIL = jsonArray1.getString("MONEYDETAIL"); //  版别
                                String SCUTCHEONSNUM = jsonArray1.getString("SCUTCHEONSNUM");// 名称
                                String MONEY = jsonArray1.getString("MONEY");// 钱数
                                String DAMAGEDSTATE = jsonArray1.getString("DAMAGEDSTATE");// 残损
                                String ID = jsonArray1.getString("ID");//id
                                String EDITIONNUM = jsonArray1.getString("EDITIONNUM");//版别
                                String MONEYNUM = jsonArray1.getString("MONEYNUM");
                                PKReonciliationEntity PKReonciliationEntity = new PKReonciliationEntity();//  每次创建对象

                                PKReonciliationEntity.setMONEY(MONEY);
                                PKReonciliationEntity.setMONEYDETAIL(MONEYDETAIL);
                                PKReonciliationEntity.setSCUTCHEONSNUM(SCUTCHEONSNUM);
                                PKReonciliationEntity.setDAMAGEDSTATE(DAMAGEDSTATE);
                                PKReonciliationEntity.setID(ID);
                                PKReonciliationEntity.setEDITIONNUM(EDITIONNUM);
                                PKReonciliationEntity.setMONEYNUM(MONEYNUM);
                                PKReonciliationEntitylist.add(PKReonciliationEntity);
                            }
                            De.setDetails(PKReonciliationEntitylist);
                        }
                        if (!NotCompleLoadDataALLlist.contains(cheid01)) {
                            NotCompleLoadDataALLlist.add(cheid01);
                        }
                        detailList001.add(De);
                    }
                    handler.sendEmptyMessage(22);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(2);
                }
            }

        }.start();
    }

    /****
     * 获取扫描数据6.1
     * {"plateNumbers":[],"checkInventory":{"atmCashReplenishment":1000,"checkId":"CK20201105103659","checkType":1,"creator":"系统管理","dataLibrary":"1","executeTime":{"date":5,"day":4,"hours":10,"minutes":36,"month":10,"seconds":59,"time":1604543819203,"timezoneOffset":-480,"year":120},"finishTime":null,"inventoryNumber":"20201105103645390","manualCorrection":"","moderator":"","otherFunds":1000,"reconciliation":1,"result":0,"scanTotalAmount":0,"transferFunds":1000,"videoSource":""}}
     */
    private void NotCompleLoadData() {

        new Thread(new Runnable() {
            public void run() {
                String result = null;
                try {

                    if (null == TaskNo || TaskNo.equals("")) {
                        handler.sendEmptyMessage(9);
                    } else {

                        sacnlist.clear();
                        sacnlist1.clear();
                        try {
                            result = UpServer.detailInfo(TaskNo, Userid);
                            JSONObject obj = JSONObject.parseObject(result);

//                            JSONObject jsonObjects = JSON.parseObject("checkInventory");
//                           String   atmCashReplenishment=jsonObjects.getString("atmCashReplenishment");
//                            CheckInventory
                            coreInventoryAmount = obj.getString("coreInventoryAmount");//  //核心库存金额
                            String repertory = obj.getString("repertory");
                            String checkInventory = obj.getString("checkInventory");
                            JSONObject jsondata = JSONObject.parseObject(checkInventory);

                            String checkType = jsondata.getString("checkType");//  // ' '查库类型：1查库，2盘库'''
                            String inventoryNumber = jsondata.getString("inventoryNumber");//  // '库存编号''
                            String dataLibrary = jsondata.getString("dataLibrary");//  // '所在库'
                            scanTotalAmount = jsondata.getString("scanTotalAmount");// '扫描合计金额'
                            atmCashReplenishment = jsondata.getString("atmCashReplenishment");//  Atm  金额
                            String checkId1 = jsondata.getString("checkId");//  查库的id
                            transferFunds = jsondata.getString("transferFunds");//  调缴款项
                            otherFunds = jsondata.getString("otherFunds");      // '其他款项'
                            int result1 = jsondata.getInteger("result");//    '结果（执行状态）：0执行中，1正常，2异常'
                            int reconciliation = jsondata.getInteger("reconciliation");//    // '对账：0未对账，1已对账'
                            String manualCorrection = jsondata.getString("manualCorrection");//  异常'异常手动调整内容'
                            String moderator = jsondata.getString("moderator");//'调整人'

                            Log.e(TAG, "===========" + moderator);

                            JSONArray arr = obj.getJSONArray("plateNumbers");
                            Log.e(TAG, "===========" + arr.size());
                            for (int i = 0; i < arr.size(); i++) {
//                                JSONObject jsonArray = arr.getJSONObject(i);
//                                String checkId = jsonArray.getString("SCUTCHEONSNUM");//  里面没有这个字段
                                NotcompeteNumState notstate = new NotcompeteNumState();
                                notstate.setNotno(arr.getString(i));
                                notstate.setState("1");
                                if (!sacnlist1.contains(arr.getString(i))) {
                                    sacnlist.add(notstate);
                                    sacnlist1.add(arr.getString(i));
                                }

                            }

                        } catch (Exception e1) {
                            handler.sendEmptyMessage(21);
                            LoadIngDialog.dismiss();
                        }
                        if (sacnlist != null && !sacnlist.equals("")) {
                            handler.sendEmptyMessage(1);//
                            LoadIngDialog.dismiss();
                        } else {
                            handler.sendEmptyMessage(3);
                            LoadIngDialog.dismiss();
                        }


                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    LoadIngDialog.dismiss();
                }

            }
        }

        ).

                start();
    }


    @Override
    protected void onResume() {
        super.onResume();
        tv_sign1.setEnabled(true);// 初始化签名不可点击// 放开签名布局
        tv_sign1.setOnClickListener(this);
        iv_sign1.setOnClickListener(this);
        String path = this.getApplicationContext().getFilesDir()
                .getAbsolutePath();
        File exdir = Environment.getExternalStorageDirectory();
        embed = "/embed.txt";
        File file = new File(exdir, embed);
        embedPath = this.getApplicationContext().getFilesDir()
                .getAbsolutePath()
                + "/";
        /* 新建签名文件TXT */
//        File file = new File(embed);
//        File file = new File(fulltule,embed);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        strPath = Environment.getExternalStorageDirectory().toString()
                + "/images/";// 存放照片的文件夹
        file = new File(strPath);
        if (!file.exists()) {
            file.mkdirs();

        }
        LoadIngDialog.show();
        NotCompleLoadData();

    }

    private String username;//  操作人

    private void InitView() {
        username = app.user.getName();
        pkreconciliationuser = (TextView) findViewById(R.id.pkreconciliationuser);
        pkreconciliationuser.setText(username);//  设置操作人
        listviewnpkConciliation = (ListView) findViewById(R.id.listviewnpkConciliation);
        listviewnpkConciliation.setOnItemClickListener(this);

        pkrecomtaskno = (TextView) findViewById(R.id.pkrecomtaskno);//   任务编号
        pkrecomtaskno.setText(TaskNo);
        PKRCMonetcout = (TextView) findViewById(R.id.PKRCMonetcout);//  核心获取库存金额

        PKReconciliationzongjine = (TextView) findViewById(R.id.PKReconciliationzongjine);//  扫描标牌金额
        PKRCA_ATMMoney = (TextView) findViewById(R.id.PKRCA_ATMMoney);//  ATM
        PKRCA_Diaojao = (TextView) findViewById(R.id.PKRCA_Diaojao);//  调交金额
        pkreconcilitaother = (TextView) findViewById(R.id.pkreconcilitaother); //  其他

        PKReconcolEntitylist.clear();

        PKReconcilia_btn_true = (Button) findViewById(R.id.PKReconcilia_btn_true);//  对账提交按钮
        PKReconcilia_btn_true.setOnClickListener(this);
        PKReconcilia_btn_true.setFocusable(false);
        PKReconcilia_btn_true.setVisibility(View.GONE);
        tv_sign1 = (TextView) findViewById(R.id.pkreconcilia_tv_sign1);// 签名提示1pkreconcilia_iv_sign1
        iv_sign1 = (ImageView) findViewById(R.id.pkreconcilia_iv_sign1);// 签名图片1

        iv_sign1.setOnClickListener(this);
        // 选中条目进行跳转
        PKRCMonetcoutinfo = (TextView) findViewById(R.id.PKRCMonetcoutinfo);//  核心库存金额明细
        PKRCMonetcoutinfo.setOnClickListener(this);

        preconcliationblack = (ImageView) findViewById(R.id.preconcliationblack);
        preconcliationblack.setOnClickListener(this);
        pk_reconcitionchagestate = (TextView) findViewById(R.id.pk_reconcitionchagestate);//  修改标牌state
        pk_reconcitionchagestate.setOnClickListener(this);
        hbt_ql_ruku_update = (Button) findViewById(R.id.hbt_ql_ruku_update);
        hbt_ql_ruku_update.setOnClickListener(this);

        PKreconciliationcheckNO = (TextView) findViewById(R.id.PKreconciliationcheckNO);//  库存编号


        hbt_ql_ruku_update = (Button) findViewById(R.id.hbt_ql_ruku_update);//更新代码
        hbt_ql_ruku_update.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.PKRCMonetcoutinfo://  跳转页面查看核心接口明细
                Intent intent = new Intent(PKReconciliationActivity.this, PKMoenyInfoActivity.class);
                if (null == TaskNo) {

                } else {
                    intent.putExtra("TaskNo", TaskNo);
                    Log.e(TAG, "跳转明细");
                    startActivity(intent);
                }

                break;

            case R.id.pkreconcilia_tv_sign1:
                qianmingLeft();//  执行签名动作
                break;

            case R.id.PKReconcilia_btn_true://   提交数据
//                PKReconciliationActivityupdata();
                UploadnImage();
                break;

            case R.id.preconcliationblack:
                PKReconciliationActivity.this.finish();
                break;

            case R.id.hbt_ql_ruku_update:

                updata();
                break;
            case R.id.pk_reconcitionchagestate:
                // 修改标牌状态

                ChangerAllBPState();
                break;

            default:
                break;
        }

    }

    /****
     * 修改所有标牌状态  传未扫
     */
    String changerBPStatestr;

    private void ChangerAllBPState() {

        dialogshowlist.clear();

        for (int i = 0; i < NotCompleLoadDataALLlist.size(); i++) {
            if (null == NotCompleLoadDataALLlist.get(i) || NotCompleLoadDataALLlist.get(i).equals("")) {
                handler.sendEmptyMessage(12);//  没获取 表数据
            } else {
                if (sacnlist1.contains(NotCompleLoadDataALLlist.get(i))) {

                    Log.e(TAG, "没有数据！！！！！！！！！");
                    NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                    notcompeteNumState.setNotno(NotCompleLoadDataALLlist.get(i));
                    notcompeteNumState.setState("1");
                    showlist.add(notcompeteNumState);
                } else {
                    dialogshowlist.add(NotCompleLoadDataALLlist.get(i));//  未扫描
                }
            }
            if (null == changerBPStatestr) {
                changerBPStatestr = dialogshowlist.get(i) + ",";
            } else {
                changerBPStatestr = changerBPStatestr + dialogshowlist.get(i) + ",";
            }

        }

//          显示dialog
        View bottomView = View.inflate(PKReconciliationActivity.this, R.layout.dialog_reconok, null);//填充ListView布局
        ListView lvCarIds = (ListView) bottomView.findViewById(R.id.listview001);//初始化ListView控件
        lvCarIds.setAdapter(new PKReconciDialogadapter(context, dialogshowlist));//ListView设置适配器
//        lvCarIds.setAdapter(new PKReconciDialog(context,NotCompleLoadDataALLlist));//ListView设置适配器
        final AlertDialog parkIdsdialog = new AlertDialog.Builder(context)
                .setTitle("标牌列表").setView(bottomView)//在这里把写好的这个listview的布局加载dialog中
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updata001();
                    }
                }).create();
        parkIdsdialog.show();

    }

    public void updata001() {
        new Thread(new Runnable() {
            public void run() {
                String result = null;
                try {
                    if (null == TaskNo || TaskNo.equals("")) {
                        handler.sendEmptyMessage(9);
                    } else if (null != Notno || Notno.equals("")) {
                        String upbpstr = "";
                        upbpstr = changerBPStatestr.substring(0, changerBPStatestr.length() - 1);
                        try {
                            result = UpServer.saveCheckInventoryDetails(TaskNo, upbpstr, Userid, UserName);
                            Log.e(TAG, "!!!!!!!!!!result" + result);
                        } catch (Exception e1) {
                        }
                        if (result.equals("00")) {
                            handler.sendEmptyMessage(6);
                        } else {
                            handler.sendEmptyMessage(5);
                        }
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(30);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(31);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(32);
                }

            }
        }

        ).

                start();
        NotCompleLoadData();
        NotCompleLoadDataALL();
        PKReconcilAdapter.notifyDataSetChanged();

    }

    /***
     * 刷新数据
     */
    private void updata() {
        NotCompleLoadData();
        NotCompleLoadDataALL();
        PKReconcilAdapter.notifyDataSetChanged();


    }


    /***
     * 回调点击某个条目
     *
     * @param position
     */
    String Notno = "";//   需要传第的标牌号码  的字符串
    WritePadDialog writeTabletDialog;

    public void qianmingLeft() {
        if (writeTabletDialog != null) {
            if (!writeTabletDialog.isShowing()) {
                writeTabletDialog.show();
            }
        } else {
            writeTabletDialog = new WritePadDialog(PKReconciliationActivity.this,
                    new DialogListener() {
                        public void refreshActivity(Object object) {
                            Bitmap map = (Bitmap) object;// 得到回传的图片
                            final String currentTime = ""
                                    + System.currentTimeMillis();
                            leftName = currentTime + ".jpg";
                            final String path = BitmapUtil.createFile(strPath,
                                    map, leftName);
                            Log.i("---LOG_TAG---", "原1" + path);
//                            final String newPic = embedPath + currentTime
//                                    + ".jpg";
                            final String newPic2 = currentTime
                                    + ".jpg";
//                            File file = new File(Environment.getExternalStorageDirectory(),newPic2);
                            final String newPic = getExternalStorageDirectory().toString() + "/images/" + currentTime + ".jpg";

                            addWatermark(leftName, newPic, path, map, tv_sign1,
                                    iv_sign1, currentTime);

                        }
                    },

                    strPath + namelist.get(0));
        }
        writeTabletDialog.show();

    }

    private Map<String, String> signInfo = new HashMap<String, String>();
    private String signTitle = "";//现场照片和对应txt文件的名称

    /**
     * 签名图片添加水印 图片bitmap map 签名人控件TextView signName 签名人图片控件 signImg 图片名字
     */
    public void addWatermark(final String picName, final String newPic,
                             final String path, Bitmap map, final TextView signName,
                             final ImageView signImg, final String currentTime) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    /*
                     * begin
					 * modify by wangmeng 2017-12-12
					 * 增加签名信息记录，方便上门服务系统中信息展示
					 */

                    /**
                     * 获取当前服务器时间
                     */
//                    String time = UpServer.getcurrentTime();
                    String time = "0001";
                    /*BufferedWriter writer = new BufferedWriter(
                            new FileWriter(embed, false));
					File file = new File(filePath);
					FileOutputStream fileOutputStream = getActivity().openFileOutput(fileName,
					Context.MODE_PRIVATE); */

//                    String fileContext = paigongdan + "_" + time + "_" + signName.getText().toString();
                    String fileContext = time + "_" + signName.getText().toString();
                    signInfo.put(currentTime, fileContext);

					/*byte[] temBytes = fileContext.getBytes();
                    fileOutputStream.write(temBytes);
					fileOutputStream.close();

					String time = UpServer.getcurrentTime();
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							embed, false));
					writer.write(paigongdan + "_" + time + "_"
							+ signName.getText().toString());
					writer.flush();
					writer.close();*/

					/*
                     *end
					 * modify by wangmeng 2017-12-12
					 * 增加签名信息记录，方便上门服务系统中信息展示
					 */
                } catch (Exception e) {

                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 调用jni  ndk 东西
                String str = operation.embed(path, embed, newPic);
                if (TextUtils.isEmpty(str)) {
                    Log.i("---------", "embed is fail");
                } else {
                    Log.i("---------", str);
                }
                PKReconciliationActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pathlist.add(newPic);// 将签名图片路径放入图片路径集合中
                        namelist.add(picName);// 将签名图片名放入图片名集合中
                        Glide.with(PKReconciliationActivity.this).load(newPic).into(signImg);
                        signName.setVisibility(View.GONE);// 隐藏签名提示
                        if (leftName != null && namelist.size() > 0) {// 开启下个功能操作   提交
                            PKReconcilia_btn_true.setVisibility(View.VISIBLE);
                            PKReconcilia_btn_true.setEnabled(true);
                            PKReconcilia_btn_true
                                    .setBackgroundResource(R.drawable.saomiao_selector);
                        }

                    }
                });
            }
        }).start();

    }

//    public static boolean checkIsImageFile(String fName) {
//        boolean isImageFile = false;
//        //获取拓展名
//        String fileEnd = fName.substring(fName.lastIndexOf(".") + 1,
//                fName.length()).toLowerCase();
//        if (fileEnd.equals("jpg") || fileEnd.equals("png") || fileEnd.equals("gif")
//                || fileEnd.equals("jpeg") || fileEnd.equals("bmp")) {
//            isImageFile = true;
//        } else {
//            isImageFile = false;
//        }
//        return isImageFile;
//    }

    /***
     * 载入空白图片
     */
    private boolean fff = false;

    private void loadDataImage() {

        final String newPic1 = getExternalStorageDirectory().toString() + "/images/" + "white1" + ".jpg";
        final String newPic11 = getExternalStorageDirectory().toString() + "/images/";
        File file1 = new File(newPic11);
        File[] files = file1.listFiles();
//             List<String> imagePaths = new ArrayList<String>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().equals("white1.jpg")) {
                fff = true;
            }
        }

        if (fff) {

        } else {// 将apk 中的图片放到文件夹
            Resources r = PKReconciliationActivity.this.getResources();
//            Inputstream is = r.openRawResource(R.drawable.my_background_image);
            InputStream is = r.openRawResource(R.mipmap.white1);
            BitmapDrawable bmpDraw = new BitmapDrawable(is);
            Bitmap bmp = bmpDraw.getBitmap();
            File file = new File(getExternalStorageDirectory().toString() + "/images/" + "white1" + ".jpg");//将要保存图片的路径

            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        final String newPic2 = getResources().getString(R.mipmap.icons_file);
//        Log.d(TAG, "!!!!!" + newPic);
//        private File file;
        final String newPic2 = getExternalStorageDirectory().toString() + "/images/" + "white1" + ".jpg";

        file = new File(strPath, signTitle + ".jpg");
        Log.e(TAG, file.getName());
        PKReconciliationActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {//white1.jpg
                namelist.add("white1" + ".jpg");
//                pathlist.add(newPic);
                if (newPic1.contains("white1.jpg")) {
                    photoPaths.add(newPic1);
                } else {
                    photoPaths.add(newPic2);

                }
            }
        });


    }

    /***
     * 上传图片的代码
     */
    public void UploadnImage() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    if ("success".equals("success")) {
                        PKReconciliationActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                imageNum = 0;
                                progressDialog.show();
                                progressDialog.setTitle("正在上传第1张图片");
                                progressDialog.setProgress(0);
                                // 给进度条
                                new Thread(new Runnable() {
                                    public void run() {
                                        try {
                                            MD5 md = new MD5();// MD5传图片
                                            // 确保图片的唯一性和完整性
                                            for (int i = 0; i < pathlist.size(); i++) {
                                                 /*
                                                 * begin
												 * modify by wangmeng 2017-12-12
												 * 往接口中添加签名信息
												 */

                                                String name = namelist.get(i).substring(0, namelist.get(i).indexOf("."));
                                                String length = md
                                                        .getMd5(pathlist.get(i));// 根据图片全路径生成MD5码
                                                String imageResult = UpServer.addHandwrittenSignature(
                                                        TaskNo, BitmapUtil
                                                                .getBytes(pathlist
                                                                        .get(i)), App.userZhanghao);
//                                                        namelist.get(i), length,
//                                                        signInfo.get(name));



                                                /*
                                                 * end
												 * modify by wangmeng 2017-12-12
												 * 往接口中添加签名信息
												 *
												 */
                                                if (imageResult.equals("00")) {
                                                    handler.sendEmptyMessage(15);//  图片提交成功
                                                } else {

                                                    handler.sendEmptyMessage(16);
                                                }
                                            }
                                        } catch (Exception e) {
                                            handler.sendEmptyMessage(3);
                                        }
                                    }
                                }).start();
                            }
                        });
                        progressDialog.dismiss();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    /**
     * 进度条显示
     */
    public void showJindu() {
        imageNum++;
        int jindu = imageNum * 100 / pathlist.size();// 计算进度条显示的数值
        progressDialog.setProgress(jindu);// 设置进度条百分比
        if (imageNum == pathlist.size()) {// 上传完毕
            progressDialog.setTitle("上传完毕...");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                        handler.sendEmptyMessage(17);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            progressDialog.setTitle("正在上传第" + (imageNum + 1) + "张图片...");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent startint = new Intent(PKReconciliationActivity.this, PKReconciliationCheckActivity.class);
        Log.e(TAG, "---------!!!----" + showlist.get(position).getState());
        Log.e(TAG, "=========!!!========" + showlist.get(position).getNotno());
        if (detailList001.size() > 0 && detailList001.get(position).getSCUTCHEONSNUM().equals(showlist.get(position).getNotno())) {
            if (showlist.get(position).getState().equals("1")) {
                Bundle bundle = new Bundle();
                bundle.putString("TaskNo", TaskNo);
                bundle.putSerializable("gates", (Serializable) detailList001.get(position).getDetails());
                bundle.putString("BPNo", showlist.get(position).getNotno());

                bundle.putString("coreInventoryAmount", coreInventoryAmount);
                bundle.putString("atmCashReplenishment", atmCashReplenishment);
                bundle.putString("transferFunds", transferFunds);
                bundle.putString("otherFunds", otherFunds);
                bundle.putString("strLibrary", strLibrary);
                startint.putExtras(bundle);
                startActivity(startint);
            } else {
                handler.sendEmptyMessage(40);
            }
        } else {
            Log.e(TAG, "-------------" + showlist.get(position).getState());
            Log.e(TAG, "=================" + showlist.get(position).getNotno());
            handler.sendEmptyMessage(41);

        }
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

    }

//
//    PKRCMonetcout.setText(coreInventoryAmount);//   设置库存金额
//    PKReconciliationzongjine.setText(scanTotalAmount);//  标牌扫描金额
//    PKRCA_ATMMoney.setText("" + atmCashReplenishment);// ATM金额
//    PKRCA_Diaojao.setText(transferFunds); // 调缴
//    pkreconcilitaother.setText(otherFunds); // 其他
//
//
//    PKreconciliationcheckNO.setText(strLibrary);//  库存编号


    /****
     * 提交信息和扫描标牌信信息要求一致
     *
     *     private List<String> NotCompleLoadDataALLlist = new ArrayList<String>();//接口6.2 获取全部的数据
     private List<NotcompeteNumState> sacnlist = new ArrayList<NotcompeteNumState>(); //  获取扫描到的数据6.1
     */
//        private static boolean checkDiffrent1(List<String> NotCompleLoadDataALLlist, List<NotcompeteNumState> sacnlist) {
//            long st = System.nanoTime();
//            System.out.println("消耗时间为：" + (System.nanoTime() - st));
//            return !list.retainAll(list1);
//        }


//    }


}
